// 2110101 : Lab8 (2545)
// dept. of computer engineering
// Chulalongkorn Univ.
import jlab.JLabIO;
public class Rational {
int numerator;
int denominator;
//--------------------------------------------------------
// an object method returning the recripocal of "this"
// rational number.
public Rational recripocate() {
Rational x = new Rational(this.denominator, this.numerator);
return x;
}
//--------------------------------------------------------
// an object method returning the result of "this"
// rational number multiplied by a.
public Rational multiply(Rational a) {
Rational x, y, z;
x = new Rational(this.numerator, a.denominator);
y = new Rational(a.numerator, this.denominator);
z = new Rational(x.numerator * y.numerator, y.denominator * x.denominator);
return z;
}
//--------------------------------------------------------
// a class method for multiplying two matrices of rational
// numbers (matrices a and b).
public static Rational[][] mulMatrix(Rational[][] a, Rational[][] b) {
Rational[][] mul = new Rational[a.length][b[0].length];
int n = a.length;
int m = b[0].length;
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
Rational sum =new Rational();
for (int k = 0; k < m; k++) {
Rational x = a[i][k].multiply(b[k][j]);
sum = sum.add(x);}
mul[i][j] = sum;
}
}
return mul;
}
//--------------------------------------------------------
// you can use the main method for your own testing (optional).
public static void main(String[] args) {
}
//--------------------------------------------------------
public Rational() {
this(0, 1);
}
public Rational(int n, int d) {
int g = gcd(n, d);
n = n / g;
d = d / g;
this.numerator = n;
this.denominator = d;
}
public Rational add(Rational a) {
int g = gcd(this.denominator, a.denominator);
int d = this.denominator / g * a.denominator;
int n = this.numerator * d / this.denominator +
a.numerator * d / a.denominator;
return new Rational(n, d);
}
public String toString() {
return this.numerator + "/" + this.denominator;
}
public static int gcd(int a, int b) {
return b == 0 ? a : gcd(b, a % b);
}
}
|